<template>
  <div class="app-container">
    <Find :OriginalFilter="{ static: true }" :formList="formList" @findClicked="findClicked" />
    <el-card shadow="never" :body-style="{ padding: '5px 10px 5px' }" class="mt10">
      <div class="flex">
        <h1 class="f16">款号库</h1>
        <JDialog
          :tableHeader="JTableHeader"
          :width="73"
          @removeOne="removeOne"
          :currentTableRow="currentTableRow"
          @confirm="confirm"
          :unEdit="false"
        />
      </div>
      <Table
        :tableHeader="tableHeader"
        :tableData="tableData"
        selection
        class="mt5"
        :isLoading="isLoading"
        @currentRow="currentRow"
        @selectList="selectTableList"
      />
    </el-card>
    <el-card shadow="never" :body-style="{ padding: '5px' }">
      <PageModule :PageData="{ total, buttonS: true }" @pageSizeChange="handleSizeChange" @pageChange="handleCurrentChange" />
    </el-card>
  </div>
</template>
<script lang="ts" setup name="OAFiling">
import { onMounted, reactive, ref, watch } from 'vue'
import 'dayjs/locale/zh-cn'
import service from '@/utils/request'
import LoginWork from '@/utils/LoginWork'
import { debounce } from 'lodash'
import fileRequest from '@/utils/fileRequest'
import { useUserInfoStore } from '@/stores/userInfo'
import { dateUtil, formatToDateTime } from '@/utils/dateUtil'
import { i18n, Jzhcn } from '@/i18n'
import JMessage from '@/utils/JMessage'
const formList = ref([
  {
    type: 'input',
    inputPlaceholder: '请输入编号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入曾用编号',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'input',
    inputPlaceholder: '请输入创建人',
    inputValue: '',
    inputLabel: ''
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '品牌',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'select',
    selectValue: '',
    selectP: '季度',
    selectLabel: '',
    selectOptions: []
  },
  {
    type: 'button',
    checkboxLabel: '置空',
    bgColor: '#1890FF'
  },
  {
    type: 'button',
    checkboxLabel: '导出'
  }
]) as any

// 表一模块
// 表一按钮
const selectedLists = ref([]) as any
const selectTableList = (selectedList: any) => {
  selectedLists.value = selectedList
}
const imgList = ref([])
const findClicked = async (content: string) => {
  if (content === '置空') {
    formList.value.forEach((item: any) => {
      item.inputValue = ''
      item.selectValue = ''
      item.dateValue = ''
    })
  }
  if (content === '导出') {
    if (selectedLists.value.length === 0) {
      JMessage.error('请勾选要导出的数据')
      return
    }
    const res = (await fileRequest.post(
      `/oaStyle/downloadOaStyle`,
      selectedLists.value.map((item: any) => item.id)
    )) as any
    const link = document.createElement('a') // 利用a标签自定义下载文件名
    let blob = new Blob([res.data]) // 创建Blob对象，设置文件类型
    link.style.display = 'none'
    //设置连接
    link.href = window.URL.createObjectURL(blob)
    const FileName = decodeURI(res.headers['content-disposition'].split(`utf-8''`)[1])
    link.download = FileName //自定义文件名字
    document.body.appendChild(link)
    //模拟点击事件
    link.click()
    document.body.removeChild(link)
  }
}
const tableHeader = ref([
  {
    label: '编号',
    prop: 'numbering'
  },
  {
    label: '曾用编号',
    prop: 'oldNumbering'
  },
  {
    type: 'selectJ',
    label: '季度',
    prop: 'season'
  },
  {
    type: 'selectJ',
    label: '品牌',
    prop: 'brand'
  },
  {
    width: 180,
    label: '客人款号',
    prop: 'custStyle'
  },
  {
    type: 'imgs',
    label: '图片',
    fixed: true,
    prop: 'photoPath',
    srcList: imgList
  },
  {
    label: '创建人',
    prop: 'createUser'
  }
])
const JTableHeader = ref([
  {
    width: 180,
    change: true,
    type: 'dateSingleSeconds',
    label: '创建时间(添加默认当前时间)',
    prop: 'createDate'
  },
  {
    width: 180,
    change: true,
    type: 'dateSingleSeconds',
    label: '修改时间(添加默认当前时间)',
    prop: 'updateDate'
  },
  {
    label: '编号',
    prop: 'numbering'
  },
  {
    label: '曾用编号',
    prop: 'oldNumbering'
  },
  {
    type: 'selectJ',
    label: '季度',
    prop: 'season',
    options: formList.value.find((item: any) => item.type === 'select' && item.selectP === '季度').selectOptions
  },
  {
    type: 'selectJ',
    label: '品牌',
    prop: 'brand',
    options: formList.value.find((item: any) => item.type === 'select' && item.selectP === '品牌').selectOptions
  },
  {
    width: 180,
    label: '客人款号',
    prop: 'custStyle'
  },
  {
    type: 'imgs',
    label: '图片',
    fixed: true,
    prop: 'photoPath',
    srcList: imgList
  }
])
const tableData = ref([])
const isLoading = ref(true)
// 分页器
const currentPage = ref(1)
const pageSize = ref(40)
const total = ref(0)
const handleSizeChange = (val: number) => {
  pageSize.value = val
  getTableList()
}
const handleCurrentChange = (val: number) => {
  currentPage.value = val
  getTableList()
}
// 获取表数据
const getTableList = debounce(async () => {
  isLoading.value = true
  let tableDataList = await service.post<any, any>('/oaStyle/getOaStyle', {
    brand: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
      ?.selectValue,
    createChoose: '1',
    createUser: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入创建人'
    )?.inputValue,
    custStyle: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '季度')
      ?.selectValue,
    numbering: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入编号'
    )?.inputValue,
    oldNumbering: formList.value.find(
      (item: any) => item.inputPlaceholder && Jzhcn.Find[item.inputPlaceholder.split('.')[1] as keyof typeof Jzhcn.Find] === '请输入曾用编号'
    )?.inputValue,
    season: formList.value.find((item: any) => item.selectP && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '季度')
      ?.selectValue,
    pageNum: currentPage.value,
    pageSize: pageSize.value
  })
  isLoading.value = false
  tableData.value = tableDataList.list.map((item: any) => {
    item.photoPath = JSON.parse(item.photoPath)
    return item
  })
  total.value = tableDataList.total
  currentRow()
}, 500)
onMounted(() => {
  getTableList()
})
watch(
  () =>
    formList.value.map((item: any) => {
      item.selectValue, item.inputValue, item.dateValue, item.checked
    }),
  () => {
    getTableList()
  }
)
// 点击表给另一张表传数据
const currentTableRow = ref({}) as any
const currentRow = async (row: any = tableData.value[0] ? tableData.value[0] : {}) => {
  currentTableRow.value = row
}
const userInfoStore = useUserInfoStore()
// Dialog确认添加/修改按钮
const confirm = async (obj: any, dialogVisible: any, title: any) => {
  const newAddImg = obj.photoPath.filter((item: any) => item.raw)
  const oldImgList = obj.photoPath.filter((item: any) => !item.raw).map((item: any) => item.url)
  console.log(newAddImg, oldImgList)

  if (title === '添加') {
    const formData = new FormData() as any
    if (newAddImg.length !== 0) {
      newAddImg.forEach((item: any) => {
        const file = new File([item.raw], item.name)
        // 创建File对象
        formData.append('photos', file)
      })
    }
    for (const key in obj) {
      if (key === 'createDate' || obj[key] === '') {
        formData.append('createDate', formatToDateTime()) // 添加文件对象及文件名
      } else if (key === 'updateDate' || obj[key] === '') {
        formData.append('updateDate', formatToDateTime()) // 添加文件对象及文件名
      } else {
        formData.append(key, obj[key]) // 添加文件对象及文件名
      }
    }
    formData.append('createUser', userInfoStore.userInfo.name1) // 添加文件对象及文件名
    const res = (await LoginWork.post(`/oaStyle/createOaStyle`, formData)) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  } else if (title === '修改') {
    const formData = new FormData() as any
    if (newAddImg.length !== 0) {
      console.log(newAddImg)
      newAddImg.forEach((item: any) => {
        const file = new File([item.raw], item.name)
        // 创建File对象
        formData.append('photos', file)
      })
    }
    for (const key in obj) {
      if (key === 'updateDate' || obj[key] === '') {
        formData.append('updateDate', formatToDateTime()) // 添加文件对象及文件名
      } else if (key === 'photoPath') {
        formData.append('photoPath', JSON.stringify(oldImgList)) // 添加文件对象及文件名
      } else if (key === 'photos' && obj[key] === null) {
        console.log('photos', obj[key])
      } else if (key === 'url' && obj[key] === null) {
        console.log('url', obj[key])
      } else if (key === 'updateUser') {
        formData.append('updateUser', userInfoStore.userInfo.name1) // 添加文件对象及文件名
      } else {
        formData.append(key, obj[key]) // 添加文件对象及文件名
      }
    }

    const res = (await LoginWork.post(`/oaStyle/updateOaStyle`, formData)) as any
    // 判断请求是否成功
    if (res.code === 200) {
      JMessage.success(res.message)
    } else {
      JMessage.error(res.message)
    }
  }
  // 关闭弹出框
  dialogVisible.value = false
  // 重新获取表格数据
  getTableList()
}
// 删除
const removeOne = async () => {
  const formData = new FormData() as any
  formData.append('id', currentTableRow.value.id) // 添加文件对象及文件名

  // 向服务器发送请求，更新外派单信息
  const res = (await LoginWork.post(`/oaStyle/deleteOaStyle`, formData)) as any
  // 判断请求是否成功
  if (res.code === 200) {
    JMessage.success(res.message)
  } else {
    JMessage.error(res.message)
  }
  // 重新获取表格数据
  getTableList()
}

onMounted(() => {
  getSelectList()
})
const getSelectList = async () => {
  let res = (await service.get<any, any>('/style/getCondition')) as any
  // custom  品牌
  res.custom.forEach((item: any) => {
    if (item === null || item === '') return
    formList.value
      .find((item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '品牌')
      .selectOptions.push({
        optionValue: item,
        optionLabel: item,
        value: item,
        label: item
      })
  })

  // season 季度
  res.season.forEach((item: any) => {
    if (item === null || item === '') return
    formList.value
      .find((item: any) => item.type === 'select' && Jzhcn.Find[item.selectP.split('.')[1] as keyof typeof Jzhcn.Find] === '季度')
      .selectOptions.push({
        optionValue: item,
        optionLabel: item,
        value: item,
        label: item
      })
  })
  // soleVendor 大底厂商
  // res.soleVendor.forEach((item: any) => {
  //   if (item === null || item === '') return
  //   formList.value
  //     .find((item: any) => item.type === 'select' && item.selectP === '大底厂商')
  //     .selectOptions.push({
  //       optionValue: item,
  //       optionLabel: item
  //     })
  // })
}
</script>
